package com.my.financial.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;

import com.my.financial.domain.User;

public class UserCheckLoginFilter implements Filter {
	private List<String> excludeUri = new ArrayList<String>();

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String excludeString = filterConfig.getInitParameter("excludeString");
		String[] arrs = excludeString.split(",");
		CollectionUtils.addAll(excludeUri, arrs);
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		if (!checkStatus(req)) {
			if (excludeUri.contains(req.getRequestURI()) || req.getRequestURI().contains(".")) {
				chain.doFilter(request, response);
				return;
			}
			resp.sendRedirect("/login");
			return;
		}
		
		if (checkStatus(req)) {
			if (!req.getRequestURI().contains("/login")
					&& !req.getRequestURI().contains("/register")) {
				chain.doFilter(request, response);
				return;
			}
			resp.sendRedirect("/index");
			return;
		}
	}

	public boolean checkStatus(HttpServletRequest req) {
		User user = (User) req.getSession().getAttribute("currUser");
		if (user == null) {
			return false;
		}
		return true;
	}

	@Override
	public void destroy() {
	}

	public List<String> getExcludeUri() {
		return excludeUri;
	}

	public void setExcludeUri(List<String> excludeUri) {
		this.excludeUri = excludeUri;
	}

}
